package com.kx.demo.jdk.collection;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author kx
 * @date 2020/4/12
 */
public class LRULinkedHashMapDemo extends LinkedHashMap {

    public final int maxCapacity;

    public LRULinkedHashMapDemo(int maxCapacity) {
        super();
        this.maxCapacity = maxCapacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > maxCapacity;
    }

    public int get(int key) {
        if (super.containsKey(key)) {
            Integer value = (Integer) super.remove(key);
            set(key, value);
            return value;
        }
        return -1;
    }

    public void set(int key, int value) {
        if (super.containsKey(key)) {
            super.remove(key);
        }
        super.put(key, value);
    }

    @Override
    public String toString() {
        return super.toString();
    }

    public static void main(String[] args) {
        LRULinkedHashMapDemo lruLinkedHashMapDemo = new LRULinkedHashMapDemo(3);
        lruLinkedHashMapDemo.set(1, 111);
        lruLinkedHashMapDemo.set(2, 222);
        lruLinkedHashMapDemo.get(1);
        lruLinkedHashMapDemo.set(3, 3333);
        lruLinkedHashMapDemo.set(4, 4444);

        System.out.println(lruLinkedHashMapDemo);
    }

}
